#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>

#define COM_MAX 256

int main()
{ 
  while(1)
  {

    //命令行提示符 && 命令行清零
    char* myshell = "[qqhsj@h2608011009 731]#";
    printf("%s", myshell);
    char command[COM_MAX];
    memset(command,0,COM_MAX);

    //获取命令行
    fgets(command, COM_MAX, stdin);
    command[strlen(command) - 1] = '\0';

    //解析命令行
    char* args[16];
    args[0] = strtok(command, " ");
    int i = 1;
    do
    {
      args[i] = strtok(NULL, " ");
      if(args[i] == NULL)
      {
        break;
      }
      i++;
    }while(1);


    //创建子进程
    pid_t ret = fork();
    if(ret < 0)
    {
      perror("fork error\n");
      
    }

    if(ret == 0)
    {
      //子进程 && 替换子进程
      execvp(args[0],args);
      exit(0);
    }
    else{
      //父进程 && 父进程等待子进程退出
      int status;
      do{
        sleep(1);
        pid_t rec = waitpid(ret, &status, WNOHANG);
        if(rec == 0)
        {
          printf("child is running\n");
        }
        else if(rec > 0 )
        {
          if(WIFEXITED(status))
          {
            printf("子进程正常退出，退出码为%d\n", WEXITSTATUS(status));
          }
          else 
          {
            printf("子进程异常退出，终止信号为%d\n", status & 0x7F);
          }
          break;
        }
        else 
        {
          perror("waitpid error\n");
          break;
        }
      }while(1);
    }
  } 
  return 0;
}
